package Assignment_2_Classes;

import java.io.*;
import java.net.*;
public class JennaKingsburyServerA2S15 {
  public static void main(String args[]) throws Exception{ 
    FileInputStream fileToSend = null;
    DatagramSocket serverSocket=new DatagramSocket(33312);
    byte[] receiveData=new byte[1024];
    byte[] sendData=new byte[1024];
    
    while(true){
      DatagramPacket receivePacket=
        new DatagramPacket(receiveData, receiveData.length);
      
      serverSocket.receive(receivePacket);
      
      String sentence=new String(receivePacket.getData());
      sentence = sentence.trim();
      
      File clientFile = new File(sentence);
      System.out.println("Server has received data: " + sentence);
      System.out.println("Data size: " + clientFile.length()); 
      System.out.println("Sending data back...");
      
      InetAddress IPAddress=receivePacket.getAddress();
      
      int port=receivePacket.getPort();
      
      sendData = ("" + clientFile.length()).getBytes();
      
      DatagramPacket sendPacket=
        new DatagramPacket(sendData, sendData.length, IPAddress, port);
      serverSocket.send(sendPacket);
      
      //This is put here to serve as a mutex so it won't send the UDP file
      //before the file name has been chosen by the client
      
      serverSocket.receive(receivePacket);
      System.out.println("It successfully waited");
      
      fileToSend = new FileInputStream(clientFile);
      int totalBytesSent = 0;
      int fileSizeSending = sendData.length;
     

        System.out.print("Sent : ");
        System.out.println(totalBytesSent + " is the totalBytesSent");
        System.out.println(clientFile.length() + " is the clientFile.length");
        while(totalBytesSent <clientFile.length()){
        sendData = new byte[1024];

        fileToSend.read(sendData);

        sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        totalBytesSent = totalBytesSent + sendData.length;
        serverSocket.send(sendPacket);
                
        //System.out.println("Total bytes sent:" + totalBytesSent/1024 + " KB");

        //Have the thread sleep to help assure that the packets arrive in order, even though this is UDP.
        Thread.sleep(5);

        }//End while
        
        System.out.println("File sent successfully.");
        fileToSend.close();
    }//End while
  }//End main
}//End server class